/*
 * @Description: 医院组页面
 * @Author: 谢涛
 * @Date: 2019-05-22 09:33:05
 * @LastEditTime: 2020-02-28 17:39:22
 * @LastEditors: Please set LastEditors
 */
import React, { Component } from 'react'
import '@ant-design/compatible/assets/index.css';
import { Form, Input, Modal, Col, Row, message,  Select, Button, Divider, } from 'antd';
import '../../../layouts/handleList.css'
import './style.css'
import { institutionsGroupApi, institutionsApi } from '@/services/basic'

class EditItem extends Component {
  constructor(props) {
    super(props);
    this.state = {
      id: undefined,
      visible: false,
      defaultOptions: [],
      defaultValue: [],
      handler: undefined,//当前正在执行的操作类型
    }
  }

  //弹出操作页面
  showModal = (handler, record) => {
    if (record) {//如果有record传过来 说明一定是查看或者更新操作
      const { id } = record;
      this.setState({ visible: true, id, handler })
      this.handleView(id);
    } else {//如果是新增操作 那直接展示弹出框 赋值操作类型
      this.setState({ visible: true, handler })
      this.queryAllYljg();
    }
  }

  //关闭操作页面
  hideModal = () => {
    this.setState({
      id: undefined,
      visible: false,
      defaultOptions: [],
      defaultValue: [],
      handler: undefined,//当前正在执行的操作类型
    }, () => 
        this.form.resetFields()
    )
  }

  //Modal框自带的取消操作
  handleCancel = () => {
    this.hideModal();
  }

  //Modal框自带的确认操作
  handleOk = () => {
    this.form.validateFields(
    ).then(
        ( values) => {
            const { handler, id } = this.state
            const requestType = handler === 'create' ? 'post' : 'put'
            let newItem = this.form.getFieldsValue();
            newItem.id = id
            institutionsGroupApi[requestType](newItem)
            .then((response) => {
                if (response.code === '1') {
                this.hideModal();
                this.form.resetFields()
                this.props.editItemDone();
                message.success("操作成功");
                } else {
                message.error(`操作失败 ${response.msg}`);
                }
            })
        }
    )
    .catch(error => {
        // eslint-disable-next-line
        console.dir(error)
    })
  }

  //一进来查所有权限
  queryAllYljg = () => {
    institutionsApi.getAll().then((res) => {
      if (res && res.length !== 0) {
        const finalOptions = res.map(item => ({
          label: item.yymc,
          value: item.id
        }))
        this.setState({ defaultOptions: finalOptions })
      }
    })
  }


  //查看单条
  handleView = (id) => {
    if (id) {
      institutionsGroupApi.get(id)
        .then((res) => {
          const { yyzmc, bz, objectList, yljgIds } = { ...res.data }
          let finalOptions = [];
          for (let item in objectList) {
            let obj = { label: objectList[item].yymc, value: objectList[item].id };
            finalOptions.push(obj)
          }

          this.setState({
            defaultOptions: finalOptions,
            defaultValue: yljgIds,
            visible: true,
            id
          }, () => console.log('defaultOptions', this.state.defaultOptions, 'defaultValue', this.state.defaultValue))
          this.form.setFieldsValue({ yyzmc, bz, yljgIds });
        })
    }
  }

  // 权限全选
    selectAll = () => {
        const options = this.state.defaultOptions
        const yljgIds = []
        options.forEach(item => {
            yljgIds.push(item.value)
        });
        this.form.setFieldsValue({ yljgIds })
    }
    // 权限反选
    selectNo = () => {
        this.form.setFieldsValue({ yljgIds: [] })
    }

  render() {
    const { handler } = this.state;

    return (
      <div className='handle-header' >
        <Modal title=""
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          width="660px"
          style={{ top: 120 }}
          maskClosable={false}
          className='handleList HospitalGroup-handle'
        >
          <div className="formHeader">
            <span className='handle-title'>{`${handler === 'view' ? '查看' : handler === 'create' ? '新增' : '更新'}医院组`}</span>
          </div>

          <Form autoComplete="off" onSubmit={this.handleOk} ref={form => this.form = form}>
            <Row gutter={8}>
              <Col span={24}>
                <Form.Item label="名称"
                    name="yyzmc"
                    getValueFromEvent={ (event) => { return event.target.value.replace(/\s+/g, ""); }}
                    rules={[{ required: true, message: '此为必填项!' }]}
                >
                    <Input
                      disabled={handler === 'view' ? true : false}
                      allowClear={handler === 'view' ? false : true}
                      placeholder='请输入' />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={24}>
                <Form.Item label="备注"
                    name="bz"
                    getValueFromEvent={ (event) => { return event.target.value.replace(/\s+/g, ""); }}
                >
                    <Input
                      disabled={handler === 'view' ? true : false}
                      allowClear={handler === 'view' ? false : true}
                      placeholder='请输入' />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={8}>
              <Col span={24}>
                <Form.Item label="选择权限" name="yljgIds" initialValue={this.state.defaultValue}>
                    <Select
                      disabled={handler === 'view' ? true : false}
                      mode="multiple"
                      showSearch
                      allowClear
                      options={this.state.defaultOptions}
                      onChange={this.onCheckChange}
                      filterOption={(input, option) =>{
                          return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      }
                      dropdownRender={menu => {
                          return <div className="">
                              {menu}
                              <Divider style={{ margin: '10px 0' }} />
                              <div style={{ textAlign: 'right' }}>
                                <Button type="primary" style={{ margin: '0 5px' }}
                                    onClick={() => { this.selectNo() } }
                                >
                                    反选
                                </Button>
                                <Button type="primary" style={{ margin: '0 5px' }}
                                    onClick={() => { this.selectAll() } }
                                >
                                    全选
                                </Button>
                                  
                              </div >

                          </div >
                      }}
                    />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Modal>
      </div>
    );
  }
}
export default EditItem